<?php
namespace App\Utility;

use EasySwoole\ORM\DbManager;
use EasySwoole\Mysqli\QueryBuilder;

class MyDb 
{
	private static $instance;
    static function getInstance(...$args)
    {
        if(!isset(self::$instance)) self::$instance = new static(...$args);
        return self::$instance;
    }

	//获取单行记录
	public function getRow($table, $where, $field='*'){
		$res = $this->execSql("SELECT {$field} FROM {$table} WHERE {$where} LIMIT 1");
		return isset($res['result'][0]) ? $res['result'][0] : [];
	}
	//获取单行单个字段
	public function getField($table, $where, $field='*'){
		$res = $this->execSql("SELECT {$field} FROM {$table} WHERE {$where} LIMIT 1");
		return isset($res['result'][0][$field]) ? $res['result'][0]['field'] : '';
	}
	//获取多行记录
	public function getAll($table, $where="1", $field='*'){
		$res = $this->execSql("SELECT {$field} FROM {$table} WHERE {$where} ");
		return isset($res['result']) ? $res['result'] : [];
	}

	//关联查询多行记录
	function getJoin($table, $field='*', $join_table, $on, $where){
		$sql = "SELECT {$field} FROM {$table} ".
			"LEFT JOIN {$join_table} ON {$on} ".
			"WHERE $where";
		$res = $this->execSql($sql);
		return isset($res['result']) ? $res['result'] : [];
	}

	//增加单行记录
	function addRow($table, $insert_data){
	    $field_str = $value_str = '';
	    foreach($insert_data as $k=>$v){
	        $f_arr[] = $k;
	        $v_arr[] = "'$v'";
	    }
	    $field_str = implode(',', $f_arr);
    	$value_str = implode(',', $v_arr);
	    $res = $this->execSql("INSERT INTO {$table}({$field_str})"." VALUE({$value_str}) ");
	    return isset($res['lastInsertId']) ? $res['lastInsertId'] : 0;
	}

	//更新记录
	function editRow($table, $update_data, $where="0"){
		$update_field = '';
		foreach($update_data as $k=>$v) $update_field .= " `$k`='$v',";
		$update_field = rtrim($update_field, ',');
		$res = $this->execSql("UPDATE {$table} SET {$update_field} WHERE {$where}");
		print_r($res);
	    return isset($res['result']) ? $res['result'] : false;
	}

	//删除记录
	function del($table, $where="0"){
		$res = $this->execSql("DELETE FROM {$table} WHERE {$where}");
		print_r($res);
		return isset($res['result']) ? $res['result'] : false;
	}


	//生成where条件
	public function whereIn($field, $items){
	    if(is_array($items)){
	        // $where_str = !empty($items) ? implode(',', $items) : "''";
	        $where_str = !empty($items) ? "'".join("','", array_values($items) )."'" : "''"; 
	        return $field." IN($where_str) ";
	    }
	    $where_str = !empty($items) ? $items : "''";
	    return $field." IN($where_str) ";
	}

	//执行SQL
	public function execSql($sql){
		$queryBuild = new QueryBuilder();
		$queryBuild->raw($sql);
		return DbManager::getInstance()->query($queryBuild, true, 'mysql')->toArray();
	}


}